﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KCMS.DataAcsess.Interfaces;
using StructureMap;
using AutoMapper;
using KCMS.BusinessLogic.Models;
using KCMS.BusinessLogic.Interfaces;


namespace KCMS.BusinessLogic.Engine
{
    public class OrderStatusService : IOrderStatusService
    {
        private IOrderStatusManager orderStatusManager = ObjectFactory.GetInstance<IOrderStatusManager>();
        public Models.OrderStatus getById(Guid id)
        {
            DataAcsess.Entitys.OrderStatusEntity orderStatusEntity = orderStatusManager.getById(id);
            return Mapper.Map<DataAcsess.Entitys.OrderStatusEntity, Models.OrderStatus>(orderStatusEntity);
        }

        public IEnumerable<Models.OrderStatus> getAll()
        {
            var model = from t in orderStatusManager.getAll()
                        select t;
            return Mapper.Map<IEnumerable<DataAcsess.Entitys.OrderStatusEntity>, IEnumerable<Models.OrderStatus>>(model);

        }

        public void update(OrderStatus orderStatus)
        {
            orderStatusManager.update(Mapper.Map<OrderStatus, DataAcsess.Entitys.OrderStatusEntity>(orderStatus));
        }


        public void save(OrderStatus orderStatus)
        {
            orderStatus.Date = DateTime.Now;
            Status status = (Status)Enum.Parse(typeof(Status), orderStatus.Status);
            switch (status)
            {
                case Status.New:
                    {
                        orderStatus.Title = "Новый";
                        break;
                    }
                case Status.InProgress:
                    {
                        orderStatus.Title = "В обработке";
                        break;
                    }
                case Status.Sent:
                    {
                        orderStatus.Title = "Отправлен";
                        break;
                    }
                case Status.Done:
                    {
                        orderStatus.Title = "Завершен";
                        break;
                    }
            }
            orderStatusManager.save(Mapper.Map<OrderStatus, DataAcsess.Entitys.OrderStatusEntity>(orderStatus));
        }


        public void delete(Guid id)
        {
            orderStatusManager.delete(id);
        }


        public OrderStatus getLastByOrder(Guid orderId)
        {
            var models =(from t in getAll()
                    where t.OrderId.Equals(orderId)
                    orderby t.Date descending
                    select t).ToList();
            return models.First();
        }


        public IEnumerable<OrderStatus> getAllByOrder(Guid orderId)
        {
            return (from t in getAll()
                    where t.OrderId.Equals(orderId)
                    select t).ToList();
        }
    }
}
